require('page/common/header/index.js')
var _catalog_service = require('service/catalog-service.js');
var _cart_service=require('service/cart-service')
const _util = require('../../../util/util');

var item = {
  init : function(){
    console.log(_util.getURLParam('itemId'));
    this.loadItemInfo();
    this.bindEvents();
    this.bindAddToCart();
    return this;
  },

  //加载Item信息
  loadItemInfo: function(){
    //向服务器发送请求，获取该itemId的item
    _catalog_service.getItemById(
      _util.getURLParam("itemId"),
      res=>{
        let item = res.data;
        console.log(item);

        $('#BackLink').html(`<a href="../../view/catalog/catalog-list.html?productId=${item.productId}&route=item">Return to ${item.productId}</a>`);
        // $('#item-img').attr('src',item.image);
        $('#item-img').attr('src','../../'+item.image);
        $('#product-desc').html(item.description);
        $('#itemId').html(item.itemId);
        $('#attrs').html(`${item.attribute1} ${item.name}`);
        $('#product-name').html(item.name);
        if(item.quantity > 0){
          $('#qtyInfo').html(`${item.quantity} in stock`);
        }else{
          $('#qtyInfo').html('Back ordered.');
        }
        $('#listprice').html(`$${item.listPrice}`);
      }, 
      errMsg=>{
        
      },
    )
  },

  //绑定事件
  bindEvents: function(){
    //Add to Cart按钮绑定单击事件
    $('#add').on('click', function(){
      //向服务器发送请求，向购物车添加商品，并进行页面跳转
      _cart_service.add_cart(
        _util.getURLParam('itemId'),
        res=>{
          //证明添加成功，进行页面跳转
          window.location.href = '../../view/cart/cart.html?redirect='+encodeURIComponent(window.location.href);
        },
        errMsg=>{

        }
      )
    })
  },
};

module.exports = item.init();